import { closeModal, openModal } from "@/hy_dev_lib/src/components/useModal";
import axios, { AxiosRequestConfig } from "axios";
import { closeMessage, openMessage } from "hy_dev_lib";
import qs from "qs";

const { tokenBaseUrl, baseURL, fileBaseURL } = SYSTEM_GLOBAL;

// let tokenBaseUrl = "http://10.32.128.252:11220/";
// let baseURL = "http://10.32.128.252:11220/";
// let baseURL = "http://10.32.128.81:8081";

export { baseURL, fileBaseURL, tokenBaseUrl };
export const href = window.location.href.split("#")[0] + "#";

// 上传文件的地址
export const uploadFilePath = baseURL + "Upload/UploadFiles";

// 文件相关 请求超时时间
export const FILE_TIME_OUT = 30 * 60 * 1000;

// 创建一个独立的axios实例
const service = axios.create({
  baseURL,
  // 定义统一的请求头部
  headers: {},
  // 配置请求超时时间
  timeout: 30 * 1000,
  // 如果用的JSONP，可以配置此参数带上cookie凭证，如果是代理和CORS不用设置
  // withCredentials: true
});
// 请求拦截
service.interceptors.request.use((config: any) => {
  //  TODO:
  // config.headers.Authorization = "Bearer " + localStorage.getItem("bearerToken");
  return config;
});

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    if (response && response.status === 200) {
      // 未登录，或登录超时
      // if (response?.data?.code === 401) {
      //   window.location.href = "/#/login";
      //   return;
      // }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    console.error(error);
    return Promise.reject(error.response);
  }
);

export default service;

export interface customOptions extends AxiosRequestConfig<any> {
  loading?: boolean;
  mock?: boolean;
  showError?: boolean; // 报错是否提示
  loadingtitle?: string; //等待提示内容
}
/** 统一处理提示信息的弹框 */
const Loading = {
  log: 0,
  number: 0,
  title: "",
  addOneLog() {
    Loading.number++;
  },
  removeOneLog() {
    Loading.number--;
  },
  // mantle: "" as any,
};
Object.defineProperty(Loading, "number", {
  get() {
    return Loading.log;
  },
  set(newValue) {
    if (newValue > 0) {
      // if (Loading.mantle) {
      //   Loading.mantle.destroy();
      // }
      // Loading.mantle = Mantle();
      openModal();
      openMessage({
        type: "loading",
        content: Loading.title,
        key: "axios_loading",
        duration: 0,
      });
    } else if (newValue === 0) {
      // 请求已完成
      closeMessage("axios_loading");
      // Loading.mantle?.destroy?.();
      closeModal();
    }

    Loading.log = newValue;
  },
});
/**
 * 核心函数，可通过它处理一切请求数据，并做横向扩展
 * @param {url} 请求地址
 * @param {params} 请求参数
 */
export function request(
  url: string,
  params: any,
  method: string,
  options: customOptions = {},
  isFormData = true
) {
  // 请求前loading
  return new Promise<any>((resolve, reject) => {
    let data = {};
    options.baseURL = (options.baseURL || baseURL) + "api/";
    const {
      loading = true,
      loadingtitle = "加载中...",
      mock,
      showError = true,
      headers,
      ...rest
    } = options;
    const headersObg: any = headers || {};
    let axiosStart = Date.now(),
      axiosEnd = 0;
    Loading.title = loadingtitle;
    // get请求使用params字段
    if (["get", "delete"].includes(method)) data = { params };
    // post请求使用data字段
    if (["post", "put"].includes(method)) {
      // const isFormData = headersObg["Content-Type"] === "multipart/form-data";
      if (isFormData) {
      }
      data = { data: isFormData ? qs.stringify(params) : params };
      // data = { data: params };
    }
    if (!headers?.Authorization && localStorage.getItem("token")) {
      headersObg.Authorization = "Bearer " + localStorage.getItem("token");
    }
    // 超过100 ms的请求出现提示框
    const promiseLoad = new Promise((resolve) => {
      setTimeout(() => {
        const showAdd = loading && axiosStart - axiosEnd > 100;
        if (showAdd) {
          Loading.addOneLog();
        }
        resolve(showAdd);
      }, 100);
    });

    service({
      url,
      method,
      ...data,
      headers: headersObg,
      ...rest,
    })
      .then((res: any) => {
        axiosEnd = Date.now();
        const { token } = res.data;
        if (token && url !== "TokenCenter/GetWebToken")
          localStorage.setItem("token", token);
        const result =
          token && url !== "TokenCenter/GetWebToken" ? res.data.data : res.data;
        const { code, msg } = result;
        if (res.status === 0 || res.status === 200) {
          // 登录失效
          if (code === 210) {
            window.location.href = "/#/login";
            return;
          }

          if (code === 230) {
            openMessage({
              type: "error",
              content: result.msg || "报错",
              key: "disconnect-msg",
            });
            setTimeout(() => {
              window.location.href = "/#/login";
            }, 2000);
            return;
          }

          if (code === 401 || code === 403) {
            // TODO:
            window.location.href = "/#/login";
            return;
            // onTokenOutTime(res);
            // reject(res);
          } else {
            // 接口返回捕获到问题 // code ===0 也算成功
            if (code && code !== 200) {
              if (showError && code !== 401)
                openMessage({
                  type: "error",
                  content: msg || result.result || "报错",
                  key: "disconnect-msg",
                });
              reject(res);
            } else {
              // 处理文件流下载文件报错
              if (options.responseType === "blob") {
                const fileReader = new FileReader();
                fileReader.readAsText(result);
                fileReader.onloadend = () => {
                  try {
                    // 转换成功 说明是普通对象数据
                    // @ts-ignore
                    const jsonRes = JSON.parse(fileReader.result);
                    if (jsonRes.code !== 200) {
                      openMessage({
                        type: "error",
                        content: msg || jsonRes.msg || "报错",
                        key: "disconnect-msg",
                      });
                      reject(res);
                    }
                  } catch (err) {
                    // 解析成对象失败，说明是正常的文件流
                    resolve(result);
                  }
                };
              } else {
                resolve(result);
              }
            }
          }
        } else {
          // 通过配置可关闭错误提示
          if (showError && code !== 401)
            openMessage({
              type: "error",
              content: msg || result.result || "报错",
              key: "disconnect-msg",
            });
          reject(res);
        }
      })
      .catch((err) => {
        if (err?.status === 401) location.href = "/#/login";
        reject(err);
      })
      .finally(() => {
        promiseLoad.then((alreadyAdd) => {
          if (alreadyAdd) {
            Loading.removeOneLog();
          }
        });
      });
  });
}
// 封装GET请求
export function get(
  url: string,
  params: any = {},
  options?: customOptions,
  isFormData?: boolean
) {
  return request(url, params, "get", options, isFormData);
}
// 封装POST请求
export function post(
  url: string,
  params: any = {},
  options?: customOptions,
  isFormData?: boolean
) {
  return request(url, params, "post", options, isFormData);
}
// 封装POST请求
export function deleteRepuest(
  url: string,
  params: any = {},
  options?: customOptions,
  isFormData?: boolean
) {
  return request(url, params, "delete", options, isFormData);
}
// 封装PUT请求
export function put(
  url: string,
  params: any = {},
  options?: customOptions,
  isFormData?: boolean
) {
  return request(url, params, "put", options, isFormData);
}

// token过期 code 401/403 跳转登陆页
export const onTokenOutTime = (err: any) => {
  const errCode = err?.data?.code || err?.status || err?.code;
  if (errCode === 401 || errCode === 403) {
    // refreshToken();
    // clearToken();
    // window.location.href = href + "/Login";
  }
};

export function downTemplate(url: string, base = baseURL) {
  try {
    const elemIF = document.createElement("iframe");
    elemIF.src = base + url;
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);
  } catch (e) {
    openMessage({
      type: "info",
      content: "下载失败！",
    });
  }
}

export function downFileWithFillUrl(url: string) {
  downTemplate(url, "");
}
